package com.sgb.kjwl.view.ui.adapter.self.publish;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.self.VideoEntity;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.swgk.core.base.CallBack;
import com.swgk.core.util.DensityUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.MyMediaUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cfk
 * @describe
 * @date
 */
public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final LayoutInflater mLayoutInflater;
    private CallBack callBack;
    private Context mContext;
    /**
     * 选择视频后返回的LocalMedia
     **/
    private List<LocalMedia> mData;
    /**
     * 本地文件List
     **/
    private List<File> fileList;
    /**
     * 网络视频和本地视频地址组合在一起的List
     **/
    private List<VideoEntity> urls;
    /**
     * 网络视频地址List
     **/
    private List<VideoEntity> neImgList;
    private Intent intent;
    private Bundle bundle;
    /**
     * 上传视频的最大张数
     **/
    private int maxSize;
    /**
     * 脚布局
     **/
    private int TYPE_FOOT = 1001;
    /**
     * 是否有弹窗 0：无    1：有
     **/
    private int type;
    public ISelectPop iSelectPop;
    RelativeLayout add_rl;

    public interface ISelectPop {
        void openPop(int index);

        void openVideo(VideoEntity url);
    }

    public void OnSelectPop(ISelectPop iSelectPop) {
        this.iSelectPop = iSelectPop;
    }

    public VideoAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
    }

    public VideoAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, CallBack callBack) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
        this.callBack = callBack;
    }

    /**
     * 需要弹窗调用
     *
     * @param context
     * @param data
     * @param urls
     * @param maxSize
     * @param type
     */
    public VideoAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, int type) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
        this.type = type;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOT) {
            View headerView = mLayoutInflater.inflate(R.layout.item_device_foot, parent, false);
            return new FootViewHolder(headerView);
        }
        View inflate = mLayoutInflater.inflate(R.layout.item_video_publish, parent, false);
        return new ViewHolder(inflate);

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder) {
            //如果地址包含http，就用网络加载视频的方式
            if (urls.get(position).getUrl().contains("http")) {
                Glide.with(mContext).load(urls.get(position).getUrl()).into(((ViewHolder) holder).img);
                ((ViewHolder) holder).time.setText(urls.get(position).getTime());
            } else {
                //没有则用本地加载视频的方式
                ((ViewHolder) holder).img.setImageBitmap(setVideoFirstImg(urls.get(position).getUrl()));
                ((ViewHolder) holder).time.setText(MyMediaUtils.getPlayTime(urls.get(position).getUrl()));
            }

            //点击视频
            ((ViewHolder) holder).img.setOnClickListener(view -> openVideoView(position));

            //点击删除按钮
            ((ViewHolder) holder).delView.setOnClickListener(v -> {
                urls.remove(position);
                notifyDataSetChanged();
            });
        } else if (holder instanceof FootViewHolder) {
            add_rl.setOnClickListener(v -> {
                if (urls.size() == maxSize) {
                    MToast.showToast(mContext, "最多选择" + maxSize + "个视频");
                } else {
                    iSelectPop.openPop(urls.size());
                }
            });
            RecyclerView.LayoutParams param = (RecyclerView.LayoutParams) add_rl.getLayoutParams();
            if (urls.size() == maxSize) {
                param.height = 0;
                param.width = 0;
                add_rl.setVisibility(View.GONE);
            } else {
                param.height = DensityUtils.dip2px(mContext, 80); // 根据具体需求场景设置
                param.width = DensityUtils.dip2px(mContext, 80);
                add_rl.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public int getItemCount() {
        if (maxSize == 1 || urls.size() == 0) {
            return 1;
        } else { //加了头布局,多一个
            return urls.size() + 1;
        }
    }

    @Override
    public int getItemViewType(int position) {
        //在第一个位置添加头
        if (urls.size() != 0) {
            if (position == urls.size()) {
                return TYPE_FOOT;
            }
        } else {
            if (position == 0) {
                return TYPE_FOOT;
            }
        }
        return super.getItemViewType(position);
    }

    //设置本地视频
    public void setDatas(List<LocalMedia> mData, List<VideoEntity> urls) {
        this.mData = mData;
        notifyDataSetChanged();
    }

    //设置本地视频
    public void setAdapterListDatas(List<LocalMedia> mData, List<VideoEntity> urls) {
        this.urls.clear();
        this.urls.removeAll(urls);
        if (neImgList.size() != 0) {
            this.urls.addAll(neImgList);
        }/* else {
            this.urls.clear();
        }*/
        this.urls.addAll(urls);
        this.mData = mData;
        notifyDataSetChanged();
    }


    /**
     * 设置视频文件List
     **/
    public void setFileList(List<File> fileList) {
        this.fileList = fileList;
    }

    /**
     * 设置网络视频List
     */
    public void setNetImgList(List<VideoEntity> netImgList) {
        if (netImgList == null) {
            this.neImgList = new ArrayList<>();
        } else {
            this.neImgList = netImgList;
            this.urls.addAll(netImgList);
        }
        notifyDataSetChanged();
    }

    /**
     * 删除网络视频List
     */
    public void removeNetImgList(List<String> albumList) {
        for (int i = 0; i < neImgList.size(); i++) {
            for (int j = 0; j < urls.size(); j++) {
                if (urls.get(j).equals(neImgList.get(i))) {
                    urls.remove(j);
                }
            }
        }
        notifyDataSetChanged();
    }

    /**
     * 获取已选择的本地文件List
     **/
    public List<File> getFileList() {
        return this.fileList;
    }

    /**
     * 获取所有的地址List，包括网络和本地
     **/
    public List<VideoEntity> getUrls() {
        return urls;
    }

    /**
     * 获取所有的地址List，包括网络和本地
     **/
    public void addUrls(VideoEntity newData) {
        urls.add(newData);
    }

    /**
     * 获取网络视频地址List
     **/
    public List<VideoEntity> getNetUrls() {
        return neImgList;
    }

    /**
     * 获取已选择的LocalMedia List
     **/
    public List<LocalMedia> getLocalMedia() {
        return mData;
    }

    /**
     * 预览
     **/
    private void openVideoView(int position) {
        if (intent == null) {
            intent = new Intent();
        }
        if (bundle == null)
            bundle = new Bundle();
       /* intent.setClass(mContext, VideoViewActivity.class);
        bundle.putSerializable(VideoViewActivity.KEY_VIDEO_URLS, (Serializable) urls);
        bundle.putInt(VideoViewActivity.KEY_VIDEO_POSITION, position);
        intent.putExtras(bundle);*/
        List<VideoBean> videoBeanList = new ArrayList<>();
        for (int i = 0; i < urls.size(); i++) {
            VideoBean videoBean = new VideoBean();
            videoBean.setCoverURL(urls.get(i).getUrl());
            videoBean.setVideoId(urls.get(i).getVideoId());
            videoBean.setTitle(urls.get(i).getTitle());
            videoBeanList.add(videoBean);
        }
        Intent intent = new Intent(mContext, PlayListActivity.class);
        intent.putExtra(PlayListActivity.VIDEOLISTBEAN, (Serializable) (Serializable) videoBeanList);
        intent.putExtra(PlayListActivity.PSO, position);
        intent.putExtra(PlayListActivity.IS_ShOW_USER, false);
        intent.putExtra(PlayListActivity.VIDEOTYPE, "fx_mine");
        mContext.startActivity(intent);
    }

    /**
     * 尾布局的viewholder
     */
    class FootViewHolder extends RecyclerView.ViewHolder {


        FootViewHolder(View itemView) {
            super(itemView);
            add_rl = itemView.findViewById(R.id.add_rl);
        }
    }


    /**
     * 正常内容的viewholder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView img;
        ImageView delView;
        TextView time;

        ViewHolder(View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.photo_img);
            delView = itemView.findViewById(R.id.delete_tv);
            time = itemView.findViewById(R.id.time);
        }
    }


    //本地视频时长
    private Bitmap setVideoFirstImg(String url) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(url);
        Bitmap bitmap = media.getFrameAtTime();
        return bitmap;
    }

    public void openVideo(int CHOOSE_REQUEST) {
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofVideo())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .maxVideoSelectNum(5)//判断还能选多少视频
                .compress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .selectionMedia(mData)
                .forResult(CHOOSE_REQUEST);
    }

}